package com.plat.api.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/11/3
 * Time: 17:48
 * Description: 目的是将m3u8数据下载下来然后转换成MP4
 */
@Slf4j
public class M3u8SolveUtil {
    /**
     * 下载m3u8文件然后转成mp4最后上传到服务器然后删除掉
     */
    public static String download(String url) throws Exception {
        String preUrlPath = url.substring(0, url.lastIndexOf("/") + 1);
        String rootPath = YmalPropertiesUtil.getValue("sys.upload.url").toString();
        HlsDownloader downLoader = new HlsDownloader(url, preUrlPath, rootPath);
        downLoader.setThreadQuantity(10);
        String fileName = "";
        String fileUrl = "";
        try {
            fileName = downLoader.download(true);
        } catch (Exception e) {

        }
        if (fileName.isEmpty()) {
            log.info("下载失败");
        } else {
            log.info(fileName);
            log.info("下载成功");
            try {
                log.info("上传中,合并直播文件完成");
                log.info(rootPath + "/" + fileName);
                //QiNiuUtil.upload(rootPath + "/" + fileName,fileName,true);
                File file = new File(rootPath + "/" + fileName);
                log.info("上传文件路径：{}",file.getPath());
                QiNiuUtil.upload(file.getPath(),fileName,true);
//                QiNiuUtil.upload(file.getPath(),fileName,true);
                fileUrl = PropertiesUtil.getQiniuFileUrl() + "/" + fileName;
                log.info("上传成功：{},完成直播制作，进入修改文件状态",fileUrl);
                String[] cmd = {"rm", "-rf", rootPath+"/"+fileName.split("\\.")[0]+"/", rootPath+"/"+fileName};
                ps(cmd);
                new File(rootPath + "/" + fileName).delete();//上传完毕删除源文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return fileUrl;
    }
    public static void ps( String[] cmd) {
        try {
            log.info("删除命令执行开始");
            Process p = Runtime.getRuntime().exec(cmd);//创建实例进程执行命令行代码
            log.info("删除命令执行成功");
            p.waitFor();
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String rootPath = YmalPropertiesUtil.getValue("sys.upload.url").toString();

        System.out.println(rootPath);
    }
}
